<script setup>
import {inject, onMounted, onUnmounted,ref} from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";

let map = null;
const parent = inject('parent');
const childValue = ref({
    lat: '',
    lng: '',
    address: ''
});

defineExpose({ childValue });
const clickHandler = (ev) =>{
    // console.log(ev.lnglat)
    childValue.value.lat = ev.lnglat.lat
    childValue.value.lng = ev.lnglat.lng

    //获取地址信息
    let lnglat = [ev.lnglat.lng, ev.lnglat.lat]
    let geocoder = new AMap.Geocoder({city: ''})
    geocoder.getAddress(lnglat, function (status, result) {
        if (status === "complete" && result.info === "OK") {
            // result为对应的地理位置详细信息
            childValue.value.address = result.regeocode.formattedAddress

            parent.getValueFromChild();
            // 清除之前标记
            map.clearMap()
            // 点标记
            let marker = new AMap.Marker({
                position: ev.lnglat,
            })
            map.add(marker)
        }
    });
}

onMounted(() => {
    window._AMapSecurityConfig = {
        securityJsCode: "d8562f773a5f6cb5e0fe7fe817e96bc5",
    };
    AMapLoader.load({
        key: "323d37eb4f4658d14b567707f4e288f5", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale", "AMap.Geocoder"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
    })
        .then((AMap) => {
            map = new AMap.Map("container", {
                // 设置地图容器id
                viewMode: "2D", // 是否为3D地图模式
                zoom: 11, // 初始化地图级别
                center: [116.397428, 39.90923], // 初始化地图中心点位置

            });
            map.on('click', clickHandler);
        })
        .catch((e) => {
            console.log(e);
        });
});

onUnmounted(() => {
    map?.destroy();
});

</script>

<template>
    <div id="container"></div>

</template>

<style scoped>
#container {
    width: 100%;
    height: 300px;
}
</style>